import { defineConfig, loadEnv } from "vite";
import reactSwc from "@vitejs/plugin-react-swc";
import { maxDisplayWidth, unitPrecision, viewportWidth } from "./src/global";
import viewport from "postcss-mobile-forever";
import autoprefixer from "autoprefixer";
import path, { resolve } from "path";
import AutoImport from "unplugin-auto-import/vite";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import svgr from "vite-plugin-svgr";

export default defineConfig(async ({ mode }) => {
  const config = loadEnv(mode, process.cwd());
  return {
    envPrefix: "VITE_",
    base: "/",
    plugins: [
      reactSwc(),
      AutoImport({
        imports: ["react", "react-router-dom", "recoil"],
        include: [/\.[tj]sx?$/, /\.js$/],
        dirs: [
          "src/api/*.ts",
          "src/assets/types/*.ts",
          "src/assets/js/*.ts",
          "src/utils/*.ts",
          "src/components/common/**",
        ],
        dts: "src/types/auto-import.d.ts",
      }),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), "src/assets/svg")],
        symbolId: "icon-[dir]-[name]",
      }),
      svgr(),
    ],
    server: {
      port: 666,
      host: "0.0.0.0",
      proxy: {
        "/api": {
          target: config.VITE_TARGET,
          changeOrigin: true,
          rewrite: (path: string) => path.replace(/^\/api/, ""),
        },
      },
    },
    resolve: {
      alias: {
        "@": resolve(__dirname, "src"),
        "@store": resolve(__dirname, "src/store"),
        "@pages": resolve(__dirname, "src/pages"),
        "@assets": resolve(__dirname, "src/assets"),
        "@styles": resolve(__dirname, "src/styles"),
        "@components": resolve(__dirname, "src/components"),
        "@utils": resolve(__dirname, "src/utils"),
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          charset: false,
          additionalData: `@import "src/styles/variables.scss"; @import "src/styles/transition.scss";`,
        },
      },
      postcss: {
        plugins: [
          autoprefixer(),
          viewport({
            viewportWidth: viewportWidth,
            mobileUnit: "vw",
            maxDisplayWidth: maxDisplayWidth,
            enableMediaQuery: false,
            desktopWidth: 600,
            landscapeWidth: 425,
            appSelector: "body",
            border: false,
            disableMobile: false,
            disableDesktop: false,
            disableLandscape: false,
            unitPrecision: unitPrecision,
            rootContainingBlockSelectorList: [],
          }),
        ],
      },
    },
  };
});
